package weaver.interfaces.htsc.hrm;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.doc.detail.util.DocDownloadCheckUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Decoder;
import weaver.conn.RecordSet;
import weaver.docs.docs.ImageFileIdUpdate;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.*;
import weaver.hrm.company.DepartmentComInfo;
import weaver.hrm.job.JobTitlesComInfo;
import weaver.hrm.resource.ResourceComInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class OrganizationSynTimeOld {
    /***
     *
     */
    public void initSyn()
    {
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        bb.writeLog("OrganizationSyn");
        RecordSet rs = new RecordSet();
        String tbrq = "" ;

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        calendar.add(Calendar.DATE, -3);
        tbrq = sdf.format(calendar.getTime());
        bb.writeLog("tbrq:"+tbrq);

        SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
        String createTimeGreater = tbrq+"T"+format2.format(new Date()) ;


        String dept_message = "";
        if(!"".equals(tbrq))
        {
            Map<String,String> headMap = new HashMap<String,String>();
            try {
                OrganizationSyn organizationSyn = new OrganizationSyn();
                String token = organizationSyn.getToken();
                headMap.put("JTXT-AUTH-TOKEN",token);
                headMap.put("JTXT-AUTH-TYPE","APP");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-获取token异常:"+e);
            }

            try{
                bb.writeLog("开始同步部门信息");
                String deptUrl = pb.getPropName("deptUrl_Inc");
                Map<String,String> map = doDeptSyn(deptUrl,createTimeGreater,headMap);
                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                dept_message = "部门同步(增量)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount;

                bb.writeLog("结束同步部门信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            String res_message = "";
            try{
                bb.writeLog("开始同步人员信息");

                updateBelongto();
                String hrmUrl = pb.getPropName("hrmUrl_Inc");

                Map<String,String> map = doHrmSyn(hrmUrl,createTimeGreater,headMap);

                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                String dataerrorcount = map.get("dataerrorcount");
                res_message = "人员同步(增量)(主岗)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount+",异常数据:"+dataerrorcount;
                bb.writeLog("结束同步人员信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            String pos_message = "";
            try{
                bb.writeLog("开始同步岗位信息");
                String jobUrl = pb.getPropName("jobUrl_Inc");
                Map<String,String> map = doPositionSyn(jobUrl,createTimeGreater,headMap);
                String updatesuccesscount = map.get("updatesuccesscount");
                String updateerrorcount = map.get("updateerrorcount");
                String insertsuccesscount = map.get("insertsuccesscount");
                String inserterrorcount = map.get("inserterrorcount");
                String exceptioncount = map.get("exceptioncount");
                String allcount = map.get("allcount");
                String dataerrorcount = map.get("dataerrorcount");

                pos_message = "人员同步(增量)(兼岗)总数:"+allcount+",新增成功:"+insertsuccesscount+",新增失败:"+inserterrorcount+",更新成功:"+updatesuccesscount+",更新失败:"+updateerrorcount+",更新异常:"+exceptioncount+",异常数据:"+dataerrorcount;
                bb.writeLog("结束同步岗位信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                String deptUrl = pb.getPropName("deptUrl_Inc");
                bb.writeLog("开始同步部门领导信息信息");
                doDeptSynToLeader(deptUrl,createTimeGreater,headMap);
                bb.writeLog("结束同步部门领导信息信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                bb.writeLog("开始同步部门矩阵信息");
                doMatrixInfo();
                bb.writeLog("结束同步部门矩阵信息");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            try{
                bb.writeLog("开始设置控件不检测");
                setSysActivexCheck();
                bb.writeLog("结束设置控件不检测");
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
            }

            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");//设置日期格式
            String modedatacreatedate = sdfDate.format(new Date());
            String modedatacreatetime = sdfTime.format(new Date());
            String modedatacreatertype = "0";

            String syn_hrmmode_cubeuuid = pb.getPropName("UF_ORGSYNTIME_CUBEUUID");
            JSONObject jsonObject = pb.getModeInfoByUUID(syn_hrmmode_cubeuuid);
            int formmodeid = Util.getIntValue(jsonObject.getString("modeid")) ;
            bb.writeLog("formmodeid:"+formmodeid);

            int userid = 1;
            String modeuuid = UUID.randomUUID().toString();
            String sql = " insert into uf_orgsyntime(tbrq,tbsj,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,modeuuid,bmtbsl,ryzgtbsl,ryjgtbsl)values\n" +
                    " ('"+modedatacreatedate+"','"+modedatacreatetime+"',"+formmodeid+","+userid+","+modedatacreatertype+",'"+modedatacreatedate+"','"+modedatacreatetime+"','"+modeuuid+"','"+dept_message+"','"+res_message+"','"+pos_message+"') ";
            bb.writeLog("sql:"+sql);
            boolean bool = rs.executeUpdate(sql);
            bb.writeLog("bool:"+bool);
            if(bool){
                rs.executeQuery( "select id from uf_orgsyntime where modeuuid='" + modeuuid + "'" );
                while (rs.next()) {
                    int id = Util.getIntValue( rs.getString( "id" ) );
                    ModeRightInfo moderight = new ModeRightInfo();
                    moderight.editModeDataShare(userid, formmodeid, id );
                }
            }
        }
        removeCache();
    }

    /***
     * @param url
     * @return
     */
    public Map<String,String> doDeptSyn(String url,String createTimeGreater,Map<String,String> headMap)
    {
        BaseBean bb = new BaseBean();
        bb.writeLog("doDeptSyn");

        int allcount = 0;
        int insertsuccesscount = 0;  //新增成功数量
        int inserterrorcount = 0;  //新增失败数量

        int updatesuccesscount = 0;  //更新成功数量
        int updateerrorcount = 0;  //更新错误数量

        int exceptioncount = 0; //异常数量

        Map<String,String> map = new HashMap<String,String>();
        JSONObject jsonObject = new JSONObject();
        bb.writeLog("createTimeGreater:"+createTimeGreater);
        jsonObject.put("createTimeGreater",createTimeGreater);
        String response = sendPost(url,jsonObject.toJSONString(),headMap);
        //默认所有部门挂在华泰集团这个分部下
        String subcompanyid1 = getSubcomIdByCode("HT0001");
        RecordSet rs = new RecordSet();
        JSONArray deptArray = JSONArray.parseArray(response);
        allcount = deptArray.size();
        for(int i=0;i<deptArray.size();i++)
        {
            JSONObject deptJson = deptArray.getJSONObject(i);
            String deptCode = deptJson.getString("deptCode");//部门编码
            String deptName = deptJson.getString("deptName");//部门名称
            String deptCodePath = deptJson.getString("deptCodePath");//部门编码
            String deptNamePath = deptJson.getString("deptNamePath");//部门名称路径
            String parentDeptCode = deptJson.getString("parentDeptCode");//上级部门编码
            String deptCity = Util.null2String(deptJson.getString("deptCity"));//部门所在城市
            String deptState = Util.null2String(deptJson.getString("deptState"));//部门状态
            //部门HRBP转换对应人员的ID
            String deptTypeName = Util.null2String(deptJson.getString("deptTypeName"));//部门类型1名称
            String deptTypeCode = Util.null2String(deptJson.getString("deptTypeCode"));//部门类型1编码
            String deptType2Name = Util.null2String(deptJson.getString("deptType2Name"));//部门类型2名称
            String deptType2Code = Util.null2String(deptJson.getString("deptType2Code"));//部门类型2编码
            String deptDepth = Util.null2String(deptJson.getString("deptDepth"));//部门树所在深度
            String deptSortNum = Util.null2String(deptJson.getString("deptSortNum"));//部门排序编码
            String isActive = Util.null2String(deptJson.getString("isActive")); //
            bb.writeLog("isActive:"+isActive);
            if(!"ACTIVE".equalsIgnoreCase(isActive)){
                deptState = "1";
            }
            String isLeafDept = "0";//是否没有子部门
            if(deptJson.getBoolean("isLeafDept"))
            {
                isLeafDept = "1";
            }
            String deptScaleLevelCode = Util.null2String(deptJson.getString("deptScaleLevelCode"));//部门规模代码
            String deptScaleLevelName = Util.null2String(deptJson.getString("deptScaleLevelName"));//部门规模名称
            String departmentType = deptJson.getString("departmentType");//自定义部门类型
            departmentType = getDepartmentType(departmentType);
            //String docNumAbbreviation = Util.null2String(deptJson.getString("docNumAbbreviation"));//部门简称
            //String docNumber = Util.null2String(deptJson.getString("docNumber"));//部门简称
            String cmpAbbre = Util.null2String(deptJson.getString("cmpAbbre"),"null");//分公司简称

            //查询上级部门对应的ID
            String supDepid = null;
            if(!"".equals(parentDeptCode)){
                supDepid = getDeptIdByCode(parentDeptCode)+"";
            }else {
                supDepid="0";
            }

            String increStatus = Util.null2String(deptJson.getString("increStatus"));
            if("CREATE".equalsIgnoreCase(increStatus) || "UPDATE".equalsIgnoreCase(increStatus))
            {
                try{
                    String deptId = getDeptIdByCode(deptCode);
                    if(!"".equals(deptId)){ //更新部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"update"+":"+deptId);
                        String deptUpdateSql =  " update hrmdepartment set departmentmark='"+deptName+"',departmentname='"+deptName+"',canceled='"+deptState+"'," +
                                " subcompanyid1='"+subcompanyid1+"',showorder='"+deptSortNum+"', supdepid='"+supDepid+"'  where departmentcode='"+deptCode+"' ";
                        bb.writeLog(deptUpdateSql);
                        boolean flag = rs.executeUpdate(deptUpdateSql);
                        if(flag)
                        {
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }

                    }else{ //插入部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"insert");
                        String deptNum = Util.null2String(deptJson.getString("deptNum"));
                        int intdeptNum = 0;
                        try{
                            if(!"".equals(deptNum)){
                                intdeptNum = Util.getIntValue(deptNum);
                            }else{
                                intdeptNum = -1;
                            }
                        }catch (Exception e){
                            bb.writeLog("OrganizationSynTime-Exception-:"+e);
                            intdeptNum = -2;
                        }
                        if(intdeptNum >0)
                        {
                            String deptInsertSql = " insert into hrmdepartment(id,departmentmark,departmentname,departmentcode," +
                                    " canceled,subcompanyid1,supdepid,showorder) values(?,?,?,?,?,?,?,?) ";
                            boolean flag = rs.executeUpdate(deptInsertSql,new Object[]{intdeptNum,deptName,deptName,deptCode,deptState,subcompanyid1,supDepid,deptSortNum});
                            if(flag)
                            {
                                insertsuccesscount++;
                            }else{
                                inserterrorcount++;
                            }
                        }
                        deptId = getDeptIdByCode(deptCode);
                    }
                    String deptDefinedId = getDeptDefineidByDeptid(deptId);
                    if(!"".equals(deptDefinedId)){
                        rs.writeLog(deptDefinedId+":"+" :update");
                        String deptUpdateSql2 = " update hrmdepartmentdefined set deptCodePath='"+deptCodePath+"',deptNamePath='"+deptNamePath+"',deptCity='"+deptCity+"',deptTypeName='"+deptTypeName+"',deptTypeCode='"+deptTypeCode+"',deptType2Name='"+deptType2Name+"',deptType2Code='"+deptType2Code+"'," +
                                " deptDepth='"+deptDepth+"',isLeafDept='"+isLeafDept+"',deptScaleLevelCode='"+deptScaleLevelCode+"',deptScaleLevelName='"+deptScaleLevelName+"',departmentType='"+departmentType+"',cmpAbbre='"+cmpAbbre+"' where id="+deptDefinedId;
                        rs.writeLog(deptUpdateSql2);
                        rs.execute(deptUpdateSql2);
                    }else{
                        rs.writeLog(deptDefinedId+":"+":insert ");
                        String deptInsertSql2 = " insert into hrmdepartmentdefined(deptid,deptCodePath,deptNamePath,deptCity," +
                                " deptTypeName,deptTypeCode,deptType2Name,deptType2Code,deptDepth,isLeafDept," +
                                " deptScaleLevelCode,deptScaleLevelName,departmentType,cmpAbbre) values(" +
                                ""+deptId+",'"+deptCodePath+"','"+deptNamePath+"','"+deptCity+"','"+deptTypeName+"'," +
                                "'"+deptTypeCode+"','"+deptType2Name+"','"+deptType2Code+"','"+deptDepth+"','"+isLeafDept+"','"+deptScaleLevelCode+"','"
                                + deptScaleLevelName+"','"+departmentType+"','"+cmpAbbre+"') ";
                        rs.writeLog(deptInsertSql2);
                        rs.execute(deptInsertSql2);
                    }

//                    String deptabbrdefid = "" ;
//                    String sql = " select id from workflow_deptabbrdef where departmentid="+deptId;
//                    rs.execute(sql);
//                    if(rs.next()){
//                        deptabbrdefid = Util.null2String(rs.getString("id"));
//                    }
//                    if(!"".equals(deptabbrdefid)){
//                        sql = " update workflow_deptabbrdef set abbr='"+ docNumAbbreviation+"' where id="+deptabbrdefid ;
//                        rs.execute(sql);
//                    }else{
//                        sql = " insert into workflow_deptabbrdef(departmentid,abbr) values("+deptId+",'"+docNumAbbreviation+"') " ;
//                        rs.execute(sql);
//                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    e.printStackTrace();
                    exceptioncount++;
                    rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
                }
            }else if("DELETE".equalsIgnoreCase(increStatus)){
                try{
                    String deptId = getDeptIdByCode(deptCode);
                    if(!"".equals(deptId)){ //更新部门数据
                        bb.writeLog(deptCode+":"+deptName+":"+"DELETE");
                        String deptUpdateSql = " update hrmdepartment set canceled=1 where id=? ";
                        boolean flag = rs.executeUpdate(deptUpdateSql,new Object[]{deptId});

                        if(flag)
                        {
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    e.printStackTrace();
                    exceptioncount++;
                    rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
                }
            }
        }
        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("allcount",allcount+"");
        return map;
    }

    /***
     * 部门同步
     * @param url
     */
    public Map<String,String> doDeptSynToLeader(String url,String createTimeGreater,Map<String,String> headMap)
    {
        OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
        BaseBean bb = new BaseBean();
        bb.writeLog("doDeptSynToLeader");
        int updatesuccesscount = 0;
        int updateerrorcount = 0;
        int exceptioncount = 0;
        Map<String,String> map = new HashMap<String,String>();
        JSONObject jsonObject = new JSONObject();
        bb.writeLog("createTimeGreater:"+createTimeGreater);
        jsonObject.put("createTimeGreater",createTimeGreater);
        String response = sendPost(url,jsonObject.toJSONString(),headMap);
//默认所有部门挂在华泰集团这个分部下
        RecordSet rs = new RecordSet();
        JSONArray deptArray = JSONArray.parseArray(response);
        for(int i=0;i<deptArray.size();i++)
        {
            JSONObject deptJson = deptArray.getJSONObject(i);
            String deptCode = deptJson.getString("deptCode");//部门编码
//部门HRBP转换对应人员的ID
            String deptHrBP = Util.null2String(deptJson.getString("deptHrBP"));//部门HRBP //主账号
            JSONArray deptHrBp2Arr = deptJson.getJSONArray("deptHrBp2");//部门HRBP2 //主账号
            deptHrBp2Arr.add(deptHrBP);
            deptHrBP = OrganizationSynUtil.getUserIdsByCodes2Main(deptHrBp2Arr);
            String deptMP = Util.null2String(deptJson.getString("deptMP"));//部门内勤
            deptMP = OrganizationSynUtil.getUserIdByCode2Main(deptMP);  //主账号
            JSONArray deptDirectorsArr = deptJson.getJSONArray("deptDirectors");//部门负责人

            JSONArray deptLeadersArr = deptJson.getJSONArray("deptLeaders");//部门分管领导  //主账号

            JSONArray departmentAreaManagers = deptJson.getJSONArray("departmentAreaManagers");//投行区域负责人

            try{
                String deptId = getDeptIdByCode(deptCode);
                String deptDirectors = OrganizationSynUtil.getUserIdsByCodes2Dept(deptDirectorsArr);
                String deptLeaders = OrganizationSynUtil.getUserIdsByCodes2Main(deptLeadersArr);
                String cohead = OrganizationSynUtil.getCohead(deptDirectorsArr);
                String txqyfzr = OrganizationSynUtil.getUserIdsByCodes2Main(departmentAreaManagers); //主账号 多人

                String deptNum = Util.null2String(deptJson.getString("deptNum")); //部门ID
                int intdeptNum = 0;
                try{
                    if(!"".equals(deptNum)){
                        intdeptNum = Util.getIntValue(deptNum);
                    }else{
                        intdeptNum = -1;
                    }
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    intdeptNum = -2;
                }
                if(intdeptNum >0)
                {
                    String deptDefinedId = getDeptDefineidByDeptid(deptId);
                    if(!"".equals(deptDefinedId))
                    {
                        rs.writeLog(deptDefinedId+":"+deptLeaders+":"+deptHrBP+":"+deptMP+":"+deptDirectors+" :update");
                        String deptUpdateSql = " update hrmdepartmentdefined set deptHrBP=?,deptMP=?,deptDirectors=?,deptLeaders=?,cohead=?,txqyfzr=? where id=? ";
                        boolean flag1 = rs.executeUpdate(deptUpdateSql,new Object[]{deptHrBP,deptMP,deptDirectors,deptLeaders,cohead,txqyfzr,deptDefinedId});
                        if(flag1){
                            updatesuccesscount++;
                        }else{
                            updateerrorcount++;
                        }
                    }
                }
                //更新部门自定义字段信息
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
                e.printStackTrace();
                exceptioncount++;
                rs.writeLog("部门编号为"+deptCode+"的数据同步失败，data:"+deptJson.toJSONString());
            }
        }
        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        return map;
    }

    /***
     * @param url
     */
    public Map<String,String> doHrmSyn(String url,String createTimeGreater,Map<String,String> headMap)
    {

        OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
        String message = "";
        int updatesuccesscount = 0;
        int updateerrorcount = 0;

        int insertsuccesscount = 0;
        int inserterrorcount = 0;

        int deletesuccesscount = 0;
        int deleteerrorcount = 0;

        int dataerrorcount = 0;

        int exceptioncount = 0;

        int allcount = 0;

        int page = 0;
        int pageSize = 300;
        Map<String,String> map = new HashMap<String,String>();
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        String subcompanyid1 = getSubcomIdByCode("HT0001");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("createTimeGreater",createTimeGreater);
        bb.writeLog("jsonObject:"+jsonObject.toJSONString());
        boolean hasNextPage = true;
        while(hasNextPage)
        {
            String response = "" ;
            try{
                String urlnew = url + "?page="+page+"&size="+pageSize ;
                response = sendPost(urlnew,jsonObject.toJSONString(),headMap);
            }catch (Exception e){
                bb.writeLog("OrganizationSynTime-Exception-:"+e);
                message = e.getMessage();
            }
            if(response !="" && !"".equals(response) && !"[]".equals(response))
            {
                JSONArray userArray = JSONArray.parseArray(response);
                allcount = allcount + userArray.size() ;
                for(int i=0;i<userArray.size();i++)
                {
                    JSONObject userJson = userArray.getJSONObject(i);
                    String empCode = Util.null2String(userJson.getString("empCode"));//员工编号
                    try{
                        String empName = Util.null2String(userJson.getString("empName"));//员工姓名

                        String empGender = Util.null2String(userJson.getString("empGender"));//员工性别
                        if ("女".equals(empGender)) {
                            empGender = "1";
                        } else {
                            empGender = "0";
                        }

                        String field8 = Util.null2String(userJson.getString("empEngName"));//员工英文名
                        String field1 = "";//微信大头像
                        String field2 = "";//微信小头像
                        String field0 = Util.null2String(userJson.getString("city"));//工作城市
                        String creator = Util.null2String(userJson.getString("creator"));//创建者工号
                        creator = OrganizationSynUtil.getUserIdByCode2Main(creator);
                        if ("".equals(creator)) {
                            creator = "1";
                        }
                        String accentEmail = Util.null2String(userJson.getString("accentEmail"),"null");//主要邮箱
                        String accentMobile = Util.null2String(userJson.getString("accentMobile"),"null");//主要手机
                        String accentPhone = Util.null2String(userJson.getString("accentPhone"),"null");//主要座机
                        String field3 = Util.null2String(userJson.getString("empEmails"),"null");//员工EMAIL
                        if (!"".equals(field3)) {
                            field3 = field3.replace("[", "").replace("]", "").replaceAll("\"", "");
                        }
                        String field4 = Util.null2String(userJson.getString("empMobiles"));//员工手机号
                        if (!"".equals(field4)) {
                            field4 = field4.replace("[", "").replace("]", "").replaceAll("\"", "");
                        }
                        String field5 = Util.null2String(userJson.getString("empPhones"));//员工固话
                        if (!"".equals(field5)) {
                            field5 = field5.replace("[", "").replace("]", "").replaceAll("\"", "");
                        }

                        String userState = Util.null2String(userJson.getString("userState"));//用户状态
                        int empSortNum = (0 - Util.getIntValue(userJson.getString("empSortNum"), 0));//员工排序号
                        String increStatus = Util.null2String(userJson.getString("increStatus"));//
                        String field6 = userJson.getString("state");//是否是外部联系人
                        String field7 = userJson.getString("comment");//备注
                        String field9 = Util.null2String(userJson.getString("empJobGrade"));//员工职级

                        String currentDate = TimeUtil.getCurrentDateString();//当前日期
                        String deptId = "";
                        String jobTitleId = "";
                        String textfield2 = "";
                        String empPositionNum = "";
                        //同步主岗数据
                        JSONObject primaryPosition = userJson.getJSONObject("primaryPosition");//主岗信息

                        if (primaryPosition != null)
                        {
                            doJobTitleSyn(primaryPosition);
                            String deptCode = primaryPosition.getString("deptCode");
                            deptId = getDeptIdByCode(deptCode);
                            String positionCode = primaryPosition.getString("positionCode");
                            if (!"".equals(positionCode) && !"".equals(deptId)) {
                                jobTitleId = getJobTitleIdByCode(positionCode, deptId);
                            }
                            textfield2 = deptCode + ";" + positionCode + ";" + empCode;
                            empPositionNum = primaryPosition.getString("empPositionNum");
                        }

                        rs.writeLog(empCode + ":" + empName + ":" + userState + "-increStatus=" + increStatus + "-textfield2:" + textfield2);
                        if ("ACTIVE".equalsIgnoreCase(userState)) {
                            userState = "1";
                        } else {
                            userState = "5";
                        }

                        if ("CREATE".equalsIgnoreCase(increStatus) || "UPDATE".equalsIgnoreCase(increStatus))
                        {
                            String userId = OrganizationSynUtil.getUserIdByCode2Main(empCode);
                            if (!"".equals(deptId) && !"".equals(jobTitleId))
                            {
                                if (!"".equals(userId))
                                {
                                    bb.writeLog(empCode + ":" + userId + ":update");
                                    String userUpdateSql1 = " update hrmresource set lastname=?,departmentid=?,subcompanyid1=?,sex=?," +
                                                            " creater=?,email=?,mobile=?,telephone=?,jobtitle=?,status=?,dsporder=?,lastmoddate=?,modified=systimestamp,textfield2=? where id=? ";
                                    boolean flag = rs.executeUpdate(userUpdateSql1, new Object[]{empName, deptId, subcompanyid1, empGender, creator, accentEmail,
                                                                    accentMobile, accentPhone, jobTitleId, userState, empSortNum, currentDate, textfield2, userId});
                                    bb.writeLog("OrganizationTimeSynHrm-update & empCode="+empCode+" & flag="+flag);
                                    if (flag) {
                                        updatesuccesscount++;

                                        try{
                                            int cusFielddataId = getCusFielddataId(userId+"", 1);
                                            if (cusFielddataId > 0) {
                                                String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                        " field5=?,field6=?,field7=?,field8=?,field9=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";

                                                bb.writeLog(userUpdateSql2);
                                                rs.executeUpdate(userUpdateSql2, new Object[]{field0, field1, field2, field3, field4, field5, field6, field7, field8, field9, userId});
                                            } else {
                                                String userInsertSql2 = " insert into cus_fielddata (scope,scopeid,id,field0,field1,field2,field3," +
                                                        " field4,field5,field6,field7,field8,field9) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?)";
                                                bb.writeLog(userInsertSql2);
                                                rs.executeUpdate(userInsertSql2, new Object[]{userId, field0, field1, field2, field3, field4, field5, field6, field7, field8, field9});
                                            }
                                        }catch (Exception e){

                                        }
                                    } else {
                                        bb.writeLog("updateerrorcount===="+empCode + ":" + userId + ":update except");
                                        updateerrorcount++;
                                    }

                                    long intresourceNum = 0;
                                    try {
                                        if (!"".equals(empPositionNum)) {
                                            intresourceNum = Long.parseLong(empPositionNum);
                                        } else {
                                            intresourceNum = -1;
                                        }
                                    } catch (Exception e) {
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                        intresourceNum = -2;
                                    }

                                    if(userId.equals(intresourceNum)){
                                        bb.writeLog("updateiderrorcount===="+empCode + ":" + userId + ":"+intresourceNum);
                                    }
                                } else {
                                    PropBean pb = new PropBean();
                                    String dynapass = Util.null2String(pb.getPropName( "PASSWORD"),"Ht123456!");
                                    String[] pwdArr = PasswordUtil.encrypt(dynapass);
                                    String newPWD = pwdArr[0];

                                    long intresourceNum = 0;
                                    try {
                                        if (!"".equals(empPositionNum)) {
                                            intresourceNum = Long.parseLong(empPositionNum);
                                        } else {
                                            intresourceNum = -1;
                                        }
                                    } catch (Exception e) {
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                        intresourceNum = -2;
                                    }
                                    bb.writeLog(empCode + "=" + intresourceNum + "=insert");

                                    try{
                                        if (intresourceNum > 0)
                                        {
                                            rs.executeProc("HrmResourceMaxId_Get", "");
                                            rs.next();
                                            userId = rs.getInt(1) + "";

                                            String userInsertSql1 = " insert into hrmresource(id,loginid,password,workcode,lastname,departmentid,subcompanyid1,sex," +
                                                    " creater,email,mobile,telephone,jobtitle,status,dsporder,systemlanguage,createdate,lastmoddate,created,modified,textfield2) " +
                                                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,systimestamp,systimestamp,?)";
                                            boolean flag = rs.executeUpdate(userInsertSql1, new Object[]{userId, empCode, newPWD, empCode, empName, deptId, subcompanyid1, empGender,
                                                    creator, accentEmail, accentMobile, accentPhone, jobTitleId, userState, empSortNum, 7, currentDate, currentDate, textfield2});
                                            bb.writeLog("OrganizationTime-id-update & empCode:"+empCode+" &--flag="+flag);

                                            if(flag)
                                            {
                                                insertsuccesscount++;
                                                try {
                                                    String sql = " update hrmresource set id=" + intresourceNum + " where id=" + userId;
                                                    bb.writeLog("sql:" + sql);
                                                    rs.execute(sql);

                                                    int cusFielddataId = getCusFielddataId(intresourceNum+"", 1);
                                                    if (cusFielddataId > 0) {
                                                        String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                                " field5=?,field6=?,field7=?,field8=?,field9=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                                        rs.executeUpdate(userUpdateSql2, new Object[]{field0, field1, field2, field3, field4, field5, field6, field7, field8, field9, userId});
                                                    } else {
                                                        String userInsertSql2 = " insert into cus_fielddata (scope,scopeid,id,field0,field1,field2,field3," +
                                                                " field4,field5,field6,field7,field8,field9) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?)";
                                                        rs.executeUpdate(userInsertSql2, new Object[]{userId, field0, field1, field2, field3, field4, field5, field6, field7, field8, field9});
                                                    }

                                                    updateColList(intresourceNum+"");
                                                } catch (Exception e) {
                                                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                                    bb.writeLog("e:" + e);
                                                }
                                            } else {
                                                inserterrorcount++;
                                            }
                                        }
                                    }catch (Exception e){
                                        dataerrorcount++;
                                        if("1".equalsIgnoreCase(userState)){
                                            bb.writeLog("OrganizationTime-dataerrorcountACTIVE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                        }else{
                                            bb.writeLog("OrganizationTime-dataerrorcountDELETE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                        }
                                    }
                                }
                            }else{
                                dataerrorcount++;
                                if("1".equalsIgnoreCase(userState)){
                                    bb.writeLog("OrganizationTime-dataerrorcountACTIVE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                }else{
                                    bb.writeLog("OrganizationTime-dataerrorcountDELETE--empCode:"+empCode+" deptId:"+deptId+" jobTitleId:"+jobTitleId);
                                }
                            }
                            if ("1".equalsIgnoreCase(userState)) {
                                String photo = Util.null2String(userJson.getString("photo"));//员工编号
                                synHrmPhoto(empCode, photo, userId);
                            }
                        } else if ("DELETE".equalsIgnoreCase(increStatus))
                        {
                            if (!"".equals(deptId) && !"".equals(jobTitleId)) {
                                String userId = OrganizationSynUtil.getUserIdByCode2Main(empCode);
                                rs.writeLog(empCode + ":" + userId + ":DELETE");
                                if (!"".equals(userId)) {
                                    String userUpdateSql1 = " update hrmresource set status=5,lastmoddate=?,modified=systimestamp where id=? ";
                                    boolean flag = rs.executeUpdate(userUpdateSql1, new Object[]{currentDate, userId});
                                    if (flag) {
                                        deletesuccesscount++;
                                    } else {
                                        deleteerrorcount++;
                                    }
                                }
                            }
                        }
                    }catch (Exception e){
                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                        e.printStackTrace();
                        message = e.getMessage();
                        rs.writeLog("人员编号"+empCode+"的数据同步失败，data:"+userJson.toJSONString());
                        exceptioncount ++ ;
                    }
                }
                if(userArray.size()<pageSize)
                {
                    hasNextPage = false;
                }
                page++;
            }else{
                bb.writeLog("777777777777777");
                hasNextPage = false;
            }
        }

        map.put("updateerrorcount",updateerrorcount+"");
        map.put("updatesuccesscount",updatesuccesscount+"");

        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");

        map.put("deletesuccesscount",deletesuccesscount+"");
        map.put("deleteerrorcount",deleteerrorcount+"");

        map.put("exceptioncount",exceptioncount+"");

        map.put("dataerrorcount",dataerrorcount+"");

        map.put("allcount",allcount+"");

        map.put("message",message);

        return map;
    }

    /***
     *
     * @param empCode
     * @param photo
     * @param userId
     */
    public void synHrmPhoto(String empCode,String photo,String userId){
        String rootpath = GCONST.getRootPath(); // "/app/ecology";
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        try{
            if(!"".equals(empCode) && empCode !=null)
            {
                String attachfilename = empCode+".jpg";
                String imagefiletype = "image/jpeg" ;
                String usericonpath = "filesystem/messager/usericon/"+ empCode;

                String usericonrealpath = rootpath+usericonpath;

                String usericonurl = "/htoa/"+usericonpath+"/"+attachfilename ;

                String usericonrealurl = rootpath+usericonpath+"/"+attachfilename ;

                File iconpath = new File(usericonrealpath);
                if (!iconpath.exists())
                {
                    iconpath.mkdirs();
                }
                if(!"".equals(photo) && photo !=null)
                {
                    boolean flag = base64ToImage(photo,usericonrealurl);
                    if(flag)
                    {
                        String resourceimageid = "" ;
                        String sql = " select resourceimageid from hrmresource where id="+userId ;
                        rs.execute(sql);
                        if(rs.next()){
                            resourceimageid = Util.null2String(rs.getString("resourceimageid"));
                        }
                        if(!"".equals(resourceimageid))
                        {
                            String imagefileidold = "" ;
                            sql = " select filerealpath,imagefileid from ImageFile where imagefileid="+resourceimageid;
                            rs.execute(sql);
                            if(rs.next()){
                                imagefileidold = Util.null2String(rs.getString("imagefileid"));
                            }
                            if(!"".equals(imagefileidold))
                            {
                                sql = " update ImageFile set filerealpath='"+usericonrealurl+"' where imagefileid ="+imagefileidold+"" ;
                                rs.writeLog("sql:"+sql);
                                rs.execute(sql);

                                if(!"".equals(userId))
                                {
                                    String fileid = "";
                                    try{
                                        fileid = DocDownloadCheckUtil.checkPermission(imagefileidold,null);
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                    }
                                    String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                    sql = " update hrmresource set messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                    rs.writeLog("sql:"+sql);
                                    rs.execute(sql);
                                }
                            }else{
                                ImageFileIdUpdate im = new ImageFileIdUpdate();
                                int imagefileid = im.getImageFileNewId();
                                rs.writeLog("imagefileid:"+imagefileid);
                                sql= " insert into ImageFile(imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                                        " values("+imagefileid+",'"+attachfilename+"','"+imagefiletype+"',1,'"+usericonrealurl+"',0,0,'"+photo.length()+"')";
                                rs.execute(sql);

                                if(!"".equals(userId))
                                {
                                    String fileid = "";
                                    try{
                                        fileid = DocDownloadCheckUtil.checkPermission(imagefileid+"",null);
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                    }

                                    String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                    sql = " update hrmresource set resourceimageid="+imagefileid+",messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                    rs.writeLog("sql:"+sql);
                                    rs.execute(sql);
                                }
                            }
                        }else{
                            ImageFileIdUpdate im = new ImageFileIdUpdate();
                            int imagefileid = im.getImageFileNewId();
                            rs.writeLog("imagefileid:"+imagefileid);
                            rs.writeLog("imagefileid:"+imagefileid);
                            sql= " insert into ImageFile(imagefileid,imagefilename,imagefiletype,imagefileused,filerealpath,iszip,isencrypt,fileSize) "+
                                    " values("+imagefileid+",'"+attachfilename+"','"+imagefiletype+"',1,'"+usericonrealurl+"',0,0,'"+photo.length()+"')";
                            rs.writeLog("sql:"+sql);
                            rs.execute(sql);

                            if(!"".equals(userId))
                            {
                                String fileid = "";
                                try{
                                    fileid = DocDownloadCheckUtil.checkPermission(imagefileid+"",null);
                                }catch (Exception e){
                                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                }

                                String fileurl = "/htoa/weaver/weaver.file.FileDownload?fileid="+fileid;
                                sql = " update hrmresource set resourceimageid="+imagefileid+",messagerurl='"+fileurl+"' where workcode='"+empCode+"'" ;
                                rs.writeLog("sql:"+sql);
                                rs.execute(sql);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
            e.printStackTrace();
        }
    }


    /**
     * @Descriptionmap 对字节数组字符串进行Base64解码并生成图片
     * @author temdy
     * @Date 2015-01-26
     * @param base64 图片Base64数据
     * @param path 图片路径
     * @return
     */
    public boolean base64ToImage(String base64,String path) {// 对字节数组字符串进行Base64解码并生成图片
        if (base64 == null) { // 图像数据为空
            return false;
        }
        BaseBean bb = new BaseBean();
        bb.writeLog("path:"+path);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(base64);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(path);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
            return false;
        }
    }

    /**
     * 岗位同步
     * @param positionJson
     */
    public void doJobTitleSyn(JSONObject positionJson){

        BaseBean bb = new BaseBean();
        bb.writeLog("-----doJobTitleSyn-----");
        if(positionJson!=null)
        {
            RecordSet rs = new RecordSet();
            String jobtitlecode = positionJson.getString("positionCode");//岗位编码
            String jobtitlename = positionJson.getString("positionName");//岗位名称
            String deptCode = positionJson.getString("deptCode");//部门编码
            bb.writeLog("岗位编码:"+jobtitlecode+",jobtitlename:"+jobtitlename+",部门编码:"+deptCode);
            if(!"".equals(deptCode) && !"".equals(jobtitlecode) && jobtitlecode !=null)
            {
                String deptId = getDeptIdByCode(deptCode);
                bb.writeLog(deptId);
                if(!"".equals(deptId))
                {
                    String jobTitlecId = getJobTitleIdByCode(jobtitlecode,deptId);
                    bb.writeLog(jobTitlecId);
                    if(!"".equals(jobTitlecId) && jobTitlecId !=null)
                    {

                        if(!"".equals(jobtitlecode) && jobtitlecode !=null)
                        {
                            bb.writeLog("update hrmjobtitles");
                            String jobtitleUpateSql = " update hrmjobtitles set jobtitlemark=?,jobtitlename=?,jobdepartmentid=? where id=? ";
                            rs.executeUpdate(jobtitleUpateSql,new Object[]{jobtitlename,jobtitlename,deptId,jobTitlecId});
                        }
                    }else{

                        if(!"".equals(jobtitlecode) && jobtitlecode !=null)
                        {
                            bb.writeLog("insert into hrmjobtitles");
                            String jobtitleInsertSql = " insert into hrmjobtitles(jobtitlemark,jobtitlename,jobdepartmentid,jobtitlecode) values(?,?,?,?)";
                            rs.executeUpdate(jobtitleInsertSql,new Object[]{jobtitlename,jobtitlename,deptId,jobtitlecode});
                        }
                    }
                }
            }
        }
    }

    public String getSecAccountIdByTextfield2(String textfield2){
        String userId = "";
        if(!"".equals(textfield2) && textfield2 !=null)
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmresource where textfield2=? ",new Object[]{textfield2});
            if(rs.next()){
                userId = Util.null2String(rs.getString("id"));
            }
        }
        return userId;
    }


    /**
     * 根据岗位编码和部门ID获取岗位ID
     * @param jobTitleCode
     * @param deptId
     * @return jobTitlecId
     */
    public String getJobTitleIdByCode(String jobTitleCode,String deptId){
        String jobTitlecId = "";
        RecordSet rs = new RecordSet();
        if(!"".equals(jobTitleCode) && !"".equals(deptId)){
            rs.executeQuery(" select id from hrmjobtitles where jobtitlecode=? and jobdepartmentid=? ",new Object[]{jobTitleCode,deptId});
            if(rs.next()){
                jobTitlecId = Util.null2String(rs.getString("id"));
            }
        }
        return jobTitlecId;
    }


    /**
     * 根据部门编码查询部门ID
     * @param deptcode
     * @return deptId
     */
    public String getDeptIdByCode(String deptcode){
        String deptId = "";
        if(deptcode!=null && !"".equals(deptcode))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmdepartment where departmentcode=? ",new Object[]{deptcode});
            if(rs.next())
            {
                deptId = Util.null2String(rs.getString("id"));
            }
        }
        return deptId;
    }

    /**
     * 根据分部编码查询分部ID
     * @param subcompanyCode
     * @return deptId
     */
    public String getSubcomIdByCode(String subcompanyCode)
    {
        String subcomId = "";
        if(subcompanyCode!=null && !"".equals(subcompanyCode))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmsubcompany where subcompanycode=? ",new Object[]{subcompanyCode});
            if(rs.next())
            {
                subcomId = Util.null2String(rs.getString("id"));
            }
        }
        return subcomId;
    }


    /**
     * 部门类型转换
     * @param departmentType
     * @return
     */
    public String getDepartmentType(String departmentType){
        String deptType = "";
        if("BASE_DEPT".equals(departmentType)){
            deptType = "0";
        }else if("BASE_SUB_DEPT".equals(departmentType)){
            deptType = "1";
        }else if("SUB_DEPT".equals(departmentType)){
            deptType = "2";
        }else if("BRANCH_DEPT".equals(departmentType)){
            deptType = "3";
        }else if("BRANCH_DEPT_BUS".equals(departmentType)){
            deptType = "4";
        }else if("SALSE_DEPT".equals(departmentType)){
            deptType = "5";
        }else{
            deptType = "6";
        }
        return deptType;
    }

    /**
     * 根据部门ID获取自定义信息ID
     * @param deptId
     * @return
     */
    public String getDeptDefineidByDeptid(String deptId){
        String deptDefineId = "";
        if(deptId !=null && !"".equals(deptId))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select id from hrmdepartmentdefined where deptid=? ",new Object[]{deptId});
            if(rs.next()){
                deptDefineId = Util.null2String(rs.getString("id"));
            }
        }
        return deptDefineId;
    }

    /**
     * 获取用户自定义数据的ID
     * @param userId
     * @param scopeid
     * @return
     */
    public int getCusFielddataId(String userId,int scopeid){
        int cusFielddataId = -1;
        if(!"".equals(userId))
        {
            RecordSet rs = new RecordSet();
            rs.executeQuery(" select seqorder from cus_fielddata where scopeid=? and id=? ",new Object[]{scopeid,userId} );
            if(rs.next()){
                cusFielddataId = rs.getInt("seqorder");
            }
        }
        return cusFielddataId;
    }






    /**
     * 根据JOSN数组对象中的人员编号查询对应的ID
     * @param jsonObjArray
     * @return
     */
    public String getCohead(JSONArray jsonObjArray)
    {
        RecordSet rs = new RecordSet();
        String userIds = "";
        if(jsonObjArray!=null && jsonObjArray.size()>0){
            for(int i=0;i<jsonObjArray.size();i++)
            {
                String empCode = jsonObjArray.getJSONObject(i).getString("empCode");
                String deptCode = jsonObjArray.getJSONObject(i).getString("deptCode");
                String positionCode = jsonObjArray.getJSONObject(i).getString("positionCode");
                String directorType = jsonObjArray.getJSONObject(i).getString("directorType");
                if("1".equals(directorType)){
                    String textfield2 = deptCode+";"+positionCode+";"+empCode;
                    rs.executeQuery(" select id from hrmresource where textfield2 =? ",new Object[]{textfield2});
                    if(rs.next())
                    {
                        String userId = Util.null2String(rs.getString("id"));
                        if(!"".equals(userId))
                        {
                            userIds += userIds== "" ? userId : ","+userId;
                        }
                    }
                }
            }
        }
        return userIds;
    }




    /**
     * 清除缓存
     */
    public void removeCache(){
        ResourceComInfo resComInfo;
        DepartmentComInfo deptComInfo;
        JobTitlesComInfo jobTitlesComInfo;
        try {
            resComInfo = new ResourceComInfo();
            resComInfo.removeResourceCache();
            deptComInfo = new DepartmentComInfo();
            deptComInfo.removeCompanyCache();
            jobTitlesComInfo = new JobTitlesComInfo();
            jobTitlesComInfo.removeCache();
        } catch (Exception e) {
            new BaseBean().writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }

    /***
     * 同步岗位数据及此账号
     */
    public Map<String,String> doPositionSyn(String url,String createTimeGreater,Map<String,String> headMap)
    {
        Map<String,String> map = new HashMap<String,String>();
        BaseBean bb = new BaseBean();
        bb.writeLog("------doPositionSyn-------");
        int updatesuccesscount = 0;
        int updateerrorcount = 0;

        int insertsuccesscount = 0;
        int inserterrorcount = 0;

        int exceptioncount = 0;

        int dataerrorcount = 0 ;

        int allcount = 0 ;

        String message = "";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("createTimeGreater",createTimeGreater);
        int page = 0;
        int pageSize = 300;

        try{
            boolean hasNextPage = true;
            while(hasNextPage)
            {
                String response = "" ;
                try {
                    String urlnew = url+"?page="+page+"&size="+pageSize ;
                    bb.writeLog("urlnew",urlnew);
                    response = sendPost(urlnew,jsonObject.toJSONString(),headMap);
                }catch (Exception e){
                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                    message = e.getMessage();
                }

                if(!"".equals(response))
                {
                    JSONArray positionArray = JSONArray.parseArray(response);
                    if(positionArray.size() >0)
                    {
                        allcount = allcount + positionArray.size();
                        for (int i = 0; i < positionArray.size(); i++)
                        {
                            JSONObject positionJson = positionArray.getJSONObject(i);
                            String positionType = Util.null2String(positionJson.get("positionType"));
                            doJobTitleSyn(positionJson);
                            if("0".equals(positionType))
                            {
                                //住账号的岗位数据同步
                                int count = doMainAccountSynTime(positionJson);
                                if(count == 1){
                                    updatesuccesscount++;
                                }else if(count == -1){
                                    updateerrorcount++;
                                }else if(count == -4){
                                    dataerrorcount++;
                                }else if(count == -3){
                                    exceptioncount++;
                                }
                            }else{
                                //次账号的岗位数据同步
                                int count = doSecAccountSynTime(positionJson);
                                if(count == 1){
                                    updatesuccesscount++;
                                }else if(count == 2){
                                    insertsuccesscount++;
                                }else if(count == -1){
                                    updateerrorcount++;
                                }else if(count == -2){
                                    inserterrorcount++;
                                }else if(count == -3){
                                    exceptioncount++;
                                }else if(count == -4){
                                    dataerrorcount++;
                                }
                            }
                        }
                        page++;
                    }else{
                        hasNextPage = false;
                    }
                }else{
                    hasNextPage = false;
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
            message = e.getMessage();
        }

        map.put("updatesuccesscount",updatesuccesscount+"");
        map.put("updateerrorcount",updateerrorcount+"");
        map.put("insertsuccesscount",insertsuccesscount+"");
        map.put("inserterrorcount",inserterrorcount+"");
        map.put("exceptioncount",exceptioncount+"");
        map.put("allcount",allcount+"");
        map.put("dataerrorcount",dataerrorcount+"");
        map.put("message",message);

        return map;
    }

    /***
     *
     * @param userJson
     * @return
     */
    public int doMainAccountSynTime(JSONObject userJson)
    {
        int count = 0;
        BaseBean bb = new BaseBean();
        PropBean pb = new PropBean();
        String HT0001 = pb.getPropName("HT0001");
        try{
            if(userJson !=null)
            {
                OrganizationSynUtil OrganizationSynUtil =  new OrganizationSynUtil();
                String subcompanyid1 = getSubcomIdByCode(HT0001);
                RecordSet rs = new RecordSet();
                String empCode = Util.null2String(userJson.getString("empCode"));//员工编号
                String positionCode = Util.null2String(userJson.getString("positionCode"));//员工编号
                String deptCode = Util.null2String(userJson.getString("deptCode"));//员工编号
                int safeLevel = Util.getIntValue(userJson.getString("safeLevel"));//安全级别
                if(!"".equals(positionCode) && !"".equals(deptCode))
                {
                    String deptId = getDeptIdByCode(deptCode);
                    String jobTitleId = getJobTitleIdByCode(positionCode,deptId);
                    String jobState = Util.null2String(userJson.getString("jobState"));//员工编号

                    String empRealWorkCity = Util.null2String(userJson.getString("empRealWorkCity"));
                    bb.writeLog("empRealWorkCity:"+empRealWorkCity);

                    if("ACTIVE".equalsIgnoreCase(jobState))
                    {
                        jobState = "1";
                    }else{
                        jobState = "5";
                    }
                    String textfield2 = deptCode+";"+positionCode+";"+empCode;
                    String userId = OrganizationSynUtil.getUserIdByCode2Main(empCode);
                    if(!"".equals(userId))
                    {
                        //人员已存在，更新操作
                        String userUpdateSql1 = " update hrmresource set departmentid='"+deptId+"',subcompanyid1='"+subcompanyid1+"',jobtitle='"+jobTitleId+"',status='"+jobState+"',textfield2='"+textfield2+"',seclevel='"+safeLevel+"'  where id='"+userId+"'";
                        bb.writeLog(userUpdateSql1);
                        boolean flag = rs.executeUpdate(userUpdateSql1);
                        if(flag){
                            count = 1;

                            String userDataSql = " update cus_fielddata set field11='"+empRealWorkCity+"' where id in(select id from hrmresource where workcode='"+empCode+"' and status=1) and scopeid=1 and scope='HrmCustomFieldByInfoType'";
                            rs.execute(userDataSql);

                        }else{
                            count = -1;
                        }
                    }
                }else {
                    count = -4;
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
            count = -3;
        }
        return count;
    }

    /**
     * 次账号同步
     * @param positionJson
     */
    public int doSecAccountSynTime(JSONObject positionJson)
    {

        OrganizationSynUtil OrganizationSynUtil = new OrganizationSynUtil();
        int count = 0;
        BaseBean bb = new BaseBean();
        bb.writeLog("------doSecAccountSynTime-------");
        try{
            if(positionJson!=null)
            {
                RecordSet rs = new RecordSet();
                String subcompanyid1 = getSubcomIdByCode("HT0001");
                String uuid = Util.null2String(positionJson.getString("uuid"));
                String empCode = Util.null2String(positionJson.getString("empCode"));
                String empName = Util.null2String(positionJson.getString("empName"));
                String belongto = OrganizationSynUtil.getUserIdByCode2Main(empCode);
                String deptCode = Util.null2String(positionJson.getString("deptCode"));
                String deptId = getDeptIdByCode(deptCode);
                String positionCode = Util.null2String(positionJson.getString("positionCode"));
                String empPositionNum = Util.null2String(positionJson.getString("empPositionNum"));


                String empRealWorkCity = Util.null2String(positionJson.getString("empRealWorkCity"));
                bb.writeLog("empRealWorkCity:"+empRealWorkCity);

                if(!"".equals(deptId) && !"".equals(positionCode))
                {
                    String jobTitleId = getJobTitleIdByCode(positionCode,deptId);
                    String jobState = Util.null2String(positionJson.getString("jobState"));
                    int safeLevel = Util.getIntValue(positionJson.getString("safeLevel"));//安全级别
                    bb.writeLog(empCode+":"+jobState+":"+positionCode);
                    if("ACTIVE".equalsIgnoreCase(jobState)){
                        jobState = "1";
                    }else{
                        jobState = "5";
                    }
                    String currentDate = TimeUtil.getCurrentDateString();//当前日期
                    String textfield2 = deptCode+";"+positionCode+";"+empCode;

                    String sex = "" ;
                    int dsporder = 0;
                    String messagerurl = "";
                    String resourceimageid = "";
                    //查询主账号的信息
                    String mainUserId = "";
                    String password = "" ;

                    rs.executeQuery(" select * from hrmresource where workcode=? and belongto is null ",new Object[]{empCode});
                    if(rs.next()) {
                        sex = Util.null2String(rs.getString("sex"));
                        dsporder = Util.getIntValue(Util.null2String(rs.getString("dsporder")), 0);
                        messagerurl = Util.null2String(rs.getString("resourceimageid"));
                        resourceimageid = Util.null2String(rs.getString("resourceimageid"));
                        mainUserId = Util.null2String(rs.getString("id"));
                    }

                    String field1 = "";//微信大头像
                    String field2 = "";//微信小头像
                    String field0 = "";//工作城市
                    String field3 = ""; //员工EMAIL
                    String field4 = ""; //员工手机号
                    String field5 = ""; //员工固话
                    String field6 =  ""; //是否是外部联系人
                    String field7 =  "";//备注
                    String field8 = "";//员工英文名
                    String field9 = ""; //员工职级
                    String field11 = "";//真实工作地
                    rs.executeQuery(" select * from cus_fielddata where scopeid=1 and id= "+mainUserId);
                    if(rs.next())
                    {
                        field0 = Util.null2String(rs.getString("field0"));
                        field3 = Util.null2String(rs.getString("field3"));
                        field4 = Util.null2String(rs.getString("field4"));
                        field5 = Util.null2String(rs.getString("field5"));
                        field6 = Util.null2String(rs.getString("field6"));
                        field7 = Util.null2String(rs.getString("field7"));
                        field8 = Util.null2String(rs.getString("field8"));
                        field9 = Util.null2String(rs.getString("field9"));
                        field11 = Util.null2String(rs.getString("field11"));
                    }

                    String userId = getSecAccountIdByTextfield2(textfield2);
                    if (!"".equals(userId))
                    {
                        bb.writeLog(empCode+":"+userId+":doSecAccountSynTime:update : "+dsporder+":"+jobState+":"+textfield2);

                        String userUpdateSql =  " update hrmresource set lastname='"+empName+"',departmentid='"+deptId+"',subcompanyid1='"+subcompanyid1+"',sex='"+sex+"'," +
                                " jobtitle='"+jobTitleId+"',status='"+jobState+"',lastmoddate='"+currentDate+"',modified=systimestamp,dsporder='"+dsporder+"',textfield1='"+uuid+"',textfield2='"+textfield2+"',workcode='"+empCode+"',seclevel='"+safeLevel+"',messagerurl='"+messagerurl+"',resourceimageid='"+resourceimageid+"' where id='"+userId+"' ";

                        bb.writeLog("userUpdateSql:"+userUpdateSql);
                        boolean flag = rs.executeUpdate(userUpdateSql);
                        if(flag)
                        {
                            count = 1;
                            if("5".equals(jobState))
                            {
                                Util.getIntValue(userId);
                            }

                            long intresourceNum = 0;
                            try{
                                if(!"".equals(empPositionNum) && !"null".equals(empPositionNum) && empPositionNum !=null){
                                    intresourceNum = Long.parseLong(empPositionNum);
                                }else{
                                    intresourceNum = -1;
                                }
                            }catch (Exception e){
                                bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                intresourceNum = -2;
                            }

                            if(intresourceNum >0)
                            {
                                if(!userId.equals(intresourceNum))
                                {
                                    try{
                                        String sql = " update hrmresource set id="+intresourceNum+" where id="+userId ;
                                        bb.writeLog("sql:"+sql);
                                        rs.execute(sql);
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                    }

                                    try{
                                        int cusFielddataId = getCusFielddataId(intresourceNum+"",1);
                                        if(cusFielddataId>0){
                                            String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                                    " field5=?,field6=?,field7=?,field8=?,field9=?,field11=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                            rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,intresourceNum});
                                        }else{
                                            String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                                    " field4,field5,field6,field7,field8,field9,field11) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?)";
                                            rs.executeUpdate(userInsertSql2,new Object[]{intresourceNum,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11});
                                        }
                                    }catch (Exception e){
                                        bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                    }
                                }
                            }

                        }else{
                            count = -1;
                        }
                    } else {

                        long intresourceNum = 0;
                        try{
                            if(!"".equals(empPositionNum) && !"null".equals(empPositionNum) && empPositionNum !=null){
                                intresourceNum = Long.parseLong(empPositionNum);
                            }else{
                                intresourceNum = -1;
                            }
                        }catch (Exception e){
                            bb.writeLog("OrganizationSynTime-Exception-:"+e);
                            intresourceNum = -2;
                        }

                        if(intresourceNum >0)
                        {
                            rs.executeProc("HrmResourceMaxId_Get", "");
                            rs.next();
                            userId = rs.getInt(1) + "";
                            rs.executeQuery(" select count(1) num from hrmresource where belongto=? ", new Object[]{belongto});
                            rs.next();
                            int num = rs.getInt("num");

                            String loginid = empCode + "czh" + num;
                            String userInsertSql =  " insert into hrmresource(id,loginid,password,lastname,departmentid,subcompanyid1,sex," +
                                    " status,systemlanguage,belongto,accounttype,textfield1,createdate,lastmoddate,created,modified," +
                                    " dsporder,textfield2,workcode,seclevel) " +
                                    " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,systimestamp,systimestamp,?,?,?,?)";

                            boolean flag = rs.executeUpdate(userInsertSql, new Object[]{userId, loginid,password, empName, deptId, subcompanyid1, sex,
                                    jobState, 7, belongto, 1, uuid, currentDate, currentDate,dsporder,textfield2,empCode,safeLevel});

                            bb.writeLog("insert-doSecAccountSynTime-empCode:"+empCode+"----num:"+num+"---mainUserId:"+mainUserId+"--intresourceNum="+intresourceNum+"--flag="+flag);

                            if(flag)
                            {
                                count = 2;
                                try{
                                    String sql = " update hrmresource set id="+intresourceNum+" where id="+userId ;
                                    bb.writeLog("sql:"+sql);
                                    rs.execute(sql);
                                }catch (Exception e){
                                    bb.writeLog("OrganizationSynTime-Exception-:"+e);
                                }

                                int cusFielddataId = getCusFielddataId(intresourceNum+"",1);
                                if(cusFielddataId>0){
                                    String userUpdateSql2 = " update cus_fielddata set field0=?,field1=?,field2=?,field3=?,field4=?," +
                                            " field5=?,field6=?,field7=?,field8=?,field9=?,field11=? where scope='HrmCustomFieldByInfoType' and scopeid=1 and id=?";
                                    rs.executeUpdate(userUpdateSql2,new Object[]{field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11,intresourceNum});
                                }else{
                                    String userInsertSql2 = " insert into cus_fielddata(scope,scopeid,id,field0,field1,field2,field3," +
                                            " field4,field5,field6,field7,field8,field9,field11) values('HrmCustomFieldByInfoType',1,?,?,?,?,?,?,?,?,?,?,?,?)";
                                    rs.executeUpdate(userInsertSql2,new Object[]{intresourceNum,field0,field1,field2,field3,field4,field5,field6,field7,field8,field9,field11});
                                }

                                updateColList(intresourceNum+"");

                            }else{
                                count = -2;
                            }
                        }
                    }
                }else{
                    count = -4;
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
            count = -3;
        }
        return count;
    }

    /****
     * @param
     */
    public void doMatrixInfo()
    {
        BaseBean bb = new BaseBean();
        try{
            RecordSet rs = new RecordSet();
            String sql =" select t.ID,l.DEPTHRBP,l.DEPTLEADERS,l.DEPTMP,l.DEPTDIRECTORS,l.COHEAD,k.id as MXRTID,l.id as DATAORDER \n" +
                    " from hrmdepartment t\n" +
                    " inner join hrmdepartmentdefined l on l.DEPTID = t.id\n" +
                    " left join Matrixtable_2 k on k.id = t.id\n" +
                    " where (t.CANCELED is null or t.CANCELED = 0) " +
                    " ";
            bb.writeLog("sql:"+sql);
            rs.execute(sql);
            Map<String,String> map = null;
            List<Map<String,String>> list = new ArrayList<Map<String,String>>();
            while (rs.next())
            {
                String id = Util.null2String(rs.getString("ID"));
                String depthrbp = Util.null2String(rs.getString("DEPTHRBP"));
                String deptleaders = Util.null2String(rs.getString("DEPTLEADERS"));
                String deptmp = Util.null2String(rs.getString("DEPTMP"));
                String deptdirectors = Util.null2String(rs.getString("DEPTDIRECTORS"));
                String cohead = Util.null2String(rs.getString("COHEAD"));
                String mxrtid = Util.null2String(rs.getString("MXRTID"));
                String dataorder = Util.null2String(rs.getString("DATAORDER"));
                map = new HashMap<String,String>();
                map.put("id",id);
                map.put("depthrbp",depthrbp);
                map.put("deptleaders",deptleaders);
                map.put("deptmp",deptmp);
                map.put("deptdirectors",deptdirectors);
                map.put("cohead",cohead);
                map.put("mxrtid",mxrtid);
                map.put("dataorder",dataorder);
                list.add(map);
            }
            bb.writeLog("list:"+list.size());
            for(int i=0;i<list.size();i++)
            {
                Map<String,String> datamap = list.get(i);
                String id = Util.null2String(datamap.get("id"));
                String depthrbp = Util.null2String(datamap.get("depthrbp"));
                String deptleaders = Util.null2String(datamap.get("deptleaders"));
                String deptmp = Util.null2String(datamap.get("deptmp"));
                String deptdirectors = Util.null2String(datamap.get("deptdirectors"));
                String cohead = Util.null2String(datamap.get("cohead"));
                String mxrtid = Util.null2String(datamap.get("mxrtid"));
                String dataorder = Util.null2String(datamap.get("dataorder"));
                bb.writeLog(id+":"+depthrbp+":"+deptleaders+":"+deptdirectors+":"+mxrtid);
                if(!"".equals(mxrtid))
                {
                    bb.writeLog(id+":"+depthrbp+":"+deptleaders+":"+deptdirectors+":"+mxrtid+":update11");
                    if(!"".equals(id))
                    {
                        sql = " update Matrixtable_2 set DEPTHRBP=?,DEPTLEADERS=?,DEPTMP=?,DEPTDIRECTORS=?,COHEAD=?  where id=?";
                        rs.executeUpdate(sql,new Object[]{depthrbp,deptleaders,deptmp,deptdirectors,cohead,id});
                    }
                }else{
                    bb.writeLog(id+":"+depthrbp+":"+deptleaders+":"+deptdirectors+":"+mxrtid+":insert22");
                    String uuid = UUID.randomUUID().toString();
                    sql = " insert into Matrixtable_2(uuid,dataorder,id,depthrbp,deptleaders,deptmp,deptdirectors,cohead) " + "" +
                            " VALUES(?,?,?,?,?,?,?,?)";
                    rs.executeUpdate(sql,new Object[]{uuid,dataorder,id,depthrbp,deptleaders,deptmp,deptdirectors,cohead});
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }

    /***
     *
     */
    public void setSysActivexCheck(){
        BaseBean bb = new BaseBean();
        try{
            RecordSet rs  = new RecordSet();
            List<String> list = new ArrayList<String>();
            String sql = " select id from hrmresource where id not in(select userid from Sysactivexcheck)\n" +
                    "  and status <4 ";
            rs.execute(sql);
            while (rs.next()){
                String userid = Util.null2String(rs.getString("id"));
                String insql = " insert into Sysactivexcheck(userid,logintype,nocheckplugin)values("+userid+",1,1)";
                list.add(insql);
            }

            if(list.size()>0)
            {
                for(String insql : list)
                {
                    rs.execute(insql);
                }
            }
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }


    /**
     *
     * @param url
     * @param params
     * @param headsMap
     * @return
     */
    public String sendPost(String url, String params,Map<String,String> headsMap){

        BaseBean bb = new BaseBean();
        String encoding = "UTF-8";
        String body = "";
//创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
//设置参数到请求对象中
        StringEntity strEntity = null;//解决中文乱码问题
        try {
            strEntity = new StringEntity(params,encoding);
        } catch (Exception e) {
            e.printStackTrace();
        }
        strEntity.setContentEncoding(encoding);
        strEntity.setContentType("application/json");
        httpPost.setEntity(strEntity);
//设置header信息
//指定报文头【Content-type】、【User-Agent】
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                bb.writeLog("key:"+key+" value:"+value);
                httpPost.addHeader(key, value);
            });
        }


//执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpPost);
//获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
//按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
           // EntityUtils.consume(entity);
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
        }
        return body;
    }

    /***
     *
     */
    public void updateBelongto(){
        BaseBean bb = new BaseBean();
        try {
            RecordSet rs = new RecordSet();
            String sql = "update hrmresource set belongto=null where status=1 and belongto = -1";
            rs.executeUpdate(sql);
        }catch (Exception e){
            bb.writeLog("OrganizationSynTime-Exception-:"+e);
        }
    }

    /***
     *
     * @param userids
     */
    public void updateColList(String userids)
    {
        RecordSet rs = new RecordSet(); //
        RecordSet rs1 = new RecordSet(); //
        BaseBean bb = new BaseBean();

        LinkedHashMap<String,String> indexMap = new LinkedHashMap<String,String>();
        indexMap.put("requestname","0");
        indexMap.put("creater","0");
        indexMap.put("workflowid","1");
        indexMap.put("requestlevel","1");
        indexMap.put("createdate","0");
        indexMap.put("receivedate","1");
        indexMap.put("currentnodeid","0");
        indexMap.put("unoperators","0");
        indexMap.put("status","1");
        indexMap.put("subwflink","1");
        indexMap.put("requestmark","1");
        indexMap.put("requestid","1");

        PropBean pb = new PropBean();
        String pageUids = pb.getPropName("PageUid") ;
        bb.writeLog("pageUids:"+pageUids);
        if(!"".equals(pageUids))
        {
            String where  ="";
            if(!"".equals(userids)){
                where = " and id in("+userids+")";
            }
            String sql = " select * from hrmresource where status=1 "+where;
            bb.writeLog("sql:"+sql);
            rs.execute(sql);
            while(rs.next())
            {
                String userid = rs.getString("id");
                bb.writeLog("userid:"+userid);
                String[] pageUidArray = pageUids.split(";");
                for(int n=0;n<pageUidArray.length;n++)
                {
                    String pageUid = pageUidArray[n];

                    int i = 0;
                    for(Map.Entry<String, String> entry : indexMap.entrySet()){
                        String mapkey = entry.getKey();
                        String mapvalue = entry.getValue();

                        String id = "";
                        sql = " select id from cloudstore_defcol where userid=? and pageuid=? and dataIndex=?";
                        bb.writeLog("sql:"+sql);
                        rs1.executeQuery(sql,new Object[]{userid,pageUid,mapkey});
                        if(rs1.next()){
                            id = Util.null2String(rs1.getString("id"));
                        }
                        bb.writeLog("id:"+id);
                        if(!"".equals(id))
                        {
                            sql = " update cloudstore_defcol set display=?,orders=? where id=?";
                            bb.writeLog("sql:"+sql);
                            boolean bool = rs1.executeUpdate(sql,new Object[]{mapvalue,i,id});
                            bb.writeLog("bool1:"+bool);
                        }else{
                            sql = " insert into cloudstore_defcol(id, dataIndex,sysid, orders, display, pageUid,userid,width) values (cloudstore_defcol_seq.nextval,?,'nullSysId',?,?,?,?,?)";
                            bb.writeLog("sql:"+sql);
                            boolean bool = rs1.executeUpdate(sql,new Object[]{mapkey,i,mapvalue,pageUid,userid,null});
                            bb.writeLog("bool2:"+bool);
                        }

                        i++;
                    }
                }
            }
        }
    }
}
